

// Vue  项目的接口文件

var express = require("express")
var router = express.Router()

var {MovieModel,mzusersModel,ShopCarModel} = require("../utils/model")
var axios  = require("axios")
var {createToken,checkToken} = require("../utils/token")

var Mock = require("mockjs")
// 禁止 使用 res.render 
router.get("/test",(req,res)=>{
    // res.send("this is vue project test interface")
    res.json({
        msg:'this is vue project test interface'
    })
})

router.get("/index",(req,res)=>{
    res.send("this is vue project test test test -index - wuhan2010 -daydayup")
    
})


// 电影接口  

router.get("/movie",(req,res)=>{
    var limit = req.query.limit * 1 || 0;   // 数字 
    MovieModel.find({},{_id:0})
    .limit(limit)
    .sort({_id:-1})
    .then(result=>{
        res.json({
            result,
            msg:'获取电影数据成功',
            code:200
        })
    })
})

router.post("/register",(req,res)=>{
    var body  =  req.body ;
    console.log(body)
    res.json({
        result:null,
        msg:"注册成功",
        code:200,
        body
    })
})


// 注册
router.post("/signup",(req,res)=>{
    const body = req.body;
    console.log(body)
    mzusersModel.findOne({
        phone:body.phone
    }).then(data=>{
        if(data){
            res.json({
                result:null,
                msg:"注册失败,手机号码已经被注册",
                code:402,
                type:0
            })
        }else{
            body.time = new Date();
            mzusersModel.insertMany(body)
            .then(result=>{
                res.json({
                    result,
                    msg:"注册成功,请登陆",
                    code:200,
                    type:1
                })
            })
        }
    })
})


// 登陆
router.post("/login",(req,res)=>{
    var body =req.body;
    mzusersModel.findOne({
        ...body
    })
    .then(result=>{
        if(result){
            body.time =  new Date()
            var token = createToken(body)
            res.json({
                result,
                code:200,
                msg:"登陆成功",
                type:1,
                token
            })
        }else{
            res.json({
                code:402,
                msg:"登录失败,手机号码或者密码不正确",
                type:0,
            })
        }
    })
    .catch(err=>{
        console.log(err)
        res.json({
            err,
            code:500,
            msg:"服务器异常",
            type:0,
        })
    })
})


// 发送验证码 
router.get("/sendcaptcha",(req,res)=>{
    var {phone} = req.query;
    mzusersModel.findOne({
        phone:phone
    })
    .then(data=>{
        if(data){
            // 发送验证码
            axios.get("http://47.104.209.44:3333/captcha/sent",{
                params:{
                   phone:phone 
                }
            })
            .then(result=>{
                // console.log(result)
                // if(result.code==200)
                if(result.data.code==200){
                    
                }
                res.json({
                    code:200,
                    msg:"验证码发送成功",
                    type:1,
                    ...result.data
                })
            })
        }else{
            res.json({
                code:402,
                msg:"手机号码暂未注册",
                type:0,
            })
        }
    })
    .catch(err=>{
        console.log(err)
        res.json({
            err,
            code:500,
            msg:"服务器异常",
            type:0,
        })
    })
})

// 校验验证码
router.get("/verifycaptcha",(req,res)=>{
    var {phone,captcha} = req.query;
    mzusersModel.findOne({
        phone:phone
    })
    .then(data=>{
        if(data){
            // 校验验证码
            axios.get("http://47.104.209.44:3333/captcha/verify",{
                params:{
                   phone:phone ,
                   captcha
                }
            })
            .then(result=>{
                var token = createToken({phone,time:new Date()})
                res.json({
                    code:200,
                    msg:"验证码验证成功",
                    type:1,
                    ...result.data,
                    token
                })
            })
        }else{
            res.json({
                code:402,
                msg:"手机号码暂未注册",
                type:0,
            })
        }
    })
    .catch(err=>{
        console.log(err)
        res.json({
            err,
            code:500,
            msg:"服务器异常",
            type:0,
        })
    })
})



// 个人信息
router.get("/getuserinfo",(req,res)=>{
    // var {phone} = req.query;
    checkToken(req,res,({
        phone
    })=>{
        mzusersModel.findOne({
            phone
        })
        .then(result=>{
            res.json({
                code:200,
                msg:"获取个人信息成功",
                type:1,
                result
            })
        })
        .catch(err=>{
            console.log(err)
            res.json({
                err,
                code:500,
                msg:"服务器异常",
                type:0,
            })
        })
    })
    
})


// 上传文件 
var multer = require("multer")
var storage = multer.diskStorage({   // 硬盘存储 
    destination: function (req, file, cb) {
      cb(null, './public/avatar')    // 文件路径 
    },
    filename: function (req, file, cb) {  // 文件名 
      cb(null, Date.now()+ "WH2010"+file.originalname)  
    }
})
var upload = multer({ storage: storage }).any()  // 不限定文件 数量

router.post("/send-avatar",upload,(req,res)=>{
    checkToken(req,res,({phone})=>{
        console.log(req.files);
        var path = req.files[0].path;
        mzusersModel.updateMany({
            phone,
        },{
            $set:{
                avatar:path
            }
        }).then(resutl=>{
            res.json({
                code:200,
                msg:"上传成功",
                avatar:path,
                type:1,
                resutl
            })
        }).catch(err=>{
            console.log(err)
            res.json({
                err,
                code:500,
                msg:"服务器异常",
                type:0,
            })
        })
        
    })
})


// 后端请求数据 
router.get("/getmaizuodata",(req,res)=>{
    var params = req.query;
    var headers = req.headers;
    axios.get("https://m.maizuo.com/gateway",{
        params,
        headers:{
            'x-host':headers['x-host'],
            'X-Client-Info': '{"a":"3000","ch":"1002","v":"5.0.4","e":"1604538483996913449009153","bc":"110100"}'
        }
    }).then(result=>{
        // console.log(result)
        res.json({
            code:200,
            msg:"获取卖座数据成功",
            result:result.data,
            type:1
        })
    }).catch(err=>{
        console.log(err)
        res.json({
            err,
            code:500,
            msg:"服务器异常",
            type:0,
        })
    })
})


router.post("/postmaizuodata",(req,res)=>{
    var body = req.body;
    var params = req.params;
    var headers = req.headers;
    axios.post("https://m.maizuo.com/gateway",body,{
        params,
        headers:{
            'x-host':headers['x-host'],
            'X-Client-Info': '{"a":"3000","ch":"1002","v":"5.0.4","e":"1604538483996913449009153","bc":"110100"}'
        }
    }).then(result=>{
        // console.log(result)
        res.json({
            code:200,
            msg:"获取卖座数据成功",
            result:result.data,
            type:1
        })
    }).catch(err=>{
        console.log(err)
        res.json({
            err,
            code:500,
            msg:"服务器异常",
            type:0,
        })
    })
})


// 模拟假数据 
const Random = Mock.Random;
router.get("/mock/data",(req,res)=>{
    const result = []
    for(var i = 0;i<250;i++){
        let obj =  {
            uid:Random.id(), 
            title:Random.csentence(5,28),  // 随机的标题 
            city:Random.city(),  // 随机的城市
            names:Random.cname(), // 名字 
            pic:Random.image('200x100', '#02adea', 'wuhan2010'),
            time:Random.date('yyyy-MM-dd') + " " + Random.time()
        }
        result.push(obj)
    }

    res.json({
        code:200,
        msg:"获取mock假数据成功",
        type:1,
        result
    })
})


// 加入购物车

router.post("/addtoshopcar",(req,res)=>{
    var body = req.body;
    console.log(body)
    // 先判断是否已经添加购物车
    // 1 有     累计再加 
    // 2. 没有  直接新增 
    ShopCarModel.findOne({
        phone:body.phone,
        gid:body.gid
    }).then(data=>{
        if(data){
            // 累计再加  
            ShopCarModel.updateMany({
                phone:body.phone,
                gid:body.gid
            },{
                // $set:{
                //     count:data.count+body.count
                // }
                $inc:{
                    count:body.count
                }
            }).then(result=>{
                res.json({
                    code:200,
                    msg:"再次增加购物车成功",
                    result:result,
                    type:1
                })
            })
        }else{
            body.time = new Date()
            ShopCarModel.insertMany(body)
            .then(result=>{
                res.json({
                    code:200,
                    msg:"新增购物车成功",
                    result:result,
                    type:1
                })
            })
        }
    }).catch(err=>{
        console.log(err)
        res.json({
            err,
            code:500,
            msg:"服务器异常",
            type:0,
        })
    })
    // res.json({
    //     code:200,
    //     msg:"添加成功"
    // })
})


// 获取购物车 
router.post("/mycartlist",(req,res)=>{
    var body  = req.body; 
    ShopCarModel.find({
        phone:body.phone
    }).then(result=>{
        res.json({
            code:200,
            msg:"查询成功",
            result:result,
            type:1
        })
    }).catch(err=>{
        console.log(err)
        res.json({
            err,
            code:500,
            msg:"服务器异常",
            type:0,
        })
    })
})

// 删除 购物车 数据 _id
router.post("/delcartone",(req,res)=>{
    var body = req.body
    ShopCarModel.remove({
        _id:body._id
    }).then(result=>{
        res.json({
            code:200,
            msg:"删除成功",
            result:result,
            type:1
        })
    }).catch(err=>{
        console.log(err)
        res.json({
            err,
            code:500,
            msg:"服务器异常",
            type:0,
        })
    })
})

// 修改 购物车 选择 
router.post("/updatecartonecheck",(req,res)=>{
    var body = req.body
    ShopCarModel.updateMany({
        _id:body._id
    },{
        $set:{
            check:body.check
        }
    }).then(result=>{
        res.json({
            code:200,
            msg:"修改成功",
            result:result,
            type:1
        })
    }).catch(err=>{
        console.log(err)
        res.json({
            err,
            code:500,
            msg:"服务器异常",
            type:0,
        })
    })
})

// 修改 购物车 数量 
router.post("/updatecartonecount",(req,res)=>{
    var body = req.body
    ShopCarModel.updateMany({
        _id:body._id
    },{
        $set:{
            count:body.count
        }
    }).then(result=>{
        res.json({
            code:200,
            msg:"修改成功",
            result:result,
            type:1
        })
    }).catch(err=>{
        console.log(err)
        res.json({
            err,
            code:500,
            msg:"服务器异常",
            type:0,
        })
    })
})
module.exports = router
